'use strict'

const { ApiController } = require('jax')

class Controller extends ApiController {
  get Model() {
    return this.ctx.model.Config
  }

  /**
   * 配置详情
   */
  async show() {
    const { ctx } = this
    const { params } = ctx

    const filter = {}

    if (params.id.length == 24) {
      filter._id = params.id
    } else {
      filter.configType = params.id.replace('-', '_')
    }

    const doc = await this.Model.findOne(filter)

    ctx.body = {
      code: 0,
      msg: 'success',
      data: doc,
    }
  }

  // 获取配置
  async getConfig() {
    const { ctx } = this
    const { configType } = ctx.params

    const returnData = await ctx.model.Config.findOne({ configType }).then((doc) => {
      let config = {}

      if (doc && doc.config) config = doc.config

      return config
    })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  // 设置配置
  async setConfig() {
    const { ctx } = this
    const { configType } = ctx.params

    const filter = {
      configType,
    }

    const newData = {
      config: ctx.request.body,
      configType,
    }

    await ctx.model.Config.updateOne(filter, newData, {
      upsert: true, // 不存在插入
      setDefaultsOnInsert: true, // 允许插入默认值
    })

    ctx.body = {
      code: 0,
      msg: 'success',
    }
  }
}

module.exports = Controller
